#include "TextureManager.h"

using namespace Managers;

TextureManager::TextureManager() : 
  AssetManager<Graphics::Texture2D>("TextureManager.log")
{
  ilInit();
}

TextureManager::~TextureManager()
{
  
}

Graphics::Texture2D *TextureManager::Load(const char *filename, unsigned int &userID, 
					  void *userData)
{
  Graphics::Texture2D *ret;
  char *cpy = new char[strlen(filename)+1];
  strcpy(cpy, filename);
  ret = Load(cpy, userID, userData);
  delete [] cpy;
  return ret;
}

Graphics::Texture2D *TextureManager::Load(char *filename, unsigned int &userID, 
					  void *userData)
{
  bool *mipmap = (bool*)userData;
  unsigned int ilID;
  ilGenImages(1, &ilID);
  ilBindImage(ilID);
  if(ilLoadImage(filename)==IL_FALSE)
    {
      ilDeleteImages(1, &ilID);
      //printf("Could not find image '%s'\n", filename);
      return NULL;
    }

  //ilOriginFunc(IL_ORIGIN_LOWER_RIGHT);
  int width = ilGetInteger(IL_IMAGE_WIDTH);
  int height = ilGetInteger(IL_IMAGE_HEIGHT);
  int bbp = ilGetInteger(IL_IMAGE_BYTES_PER_PIXEL);
  bool alpha;
  if(bbp == 4)
    {
      alpha = true;
      if(ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE)==IL_FALSE)
	{
	  printf("Could not convert '%s' to RGBA\n", filename);
	  ilDeleteImages(1, &ilID);
	  return NULL;
	}
    }
  else if(bbp == 3)
    {
      alpha = false;
      if(ilConvertImage(IL_RGB, IL_UNSIGNED_BYTE)==IL_FALSE)
	{
	  printf("Could not convert '%s' to RGB\n", filename);
	  ilDeleteImages(1, &ilID);
	  return NULL;
	}
    }
  else
    {
      printf("'%s' is not a RGB image\n", filename);
      ilDeleteImages(1, &ilID);
      return NULL;
    }

  Graphics::Texture2D *created = new Graphics::Texture2D(
							 width, height, 
							 ilGetData(),
							 alpha,
							 &mipmap);

  ilDeleteImages(1, &ilID);
  userID = uIDCount;
  uIDCount++;
  return created;
}
